package com.lbb.springboot.auto.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lbb.springboot.auto.util.FormData.FieldData;


public class DomysqlBean {

    final static String sql = "SELECT COLUMN_NAME,COLUMN_TYPE,COLUMN_COMMENT FROM information_schema.COLUMNS where TABLE_SCHEMA='%s' and TABLE_NAME='%s' order by ORDINAL_POSITION;";
    static String[] list;

    static String dbname = "xcx";

    static List<FieldData> lf = new ArrayList<FieldData>();

//	static String tableName="js_news";

    /**
     * @param args
     * @throws SQLException
     */
    public static void main(String[] args) throws SQLException {
        /*
         * String dbname=Cfg.getPropertiesVal("dbname"); String
         * dto=Cfg.getPropertiesVal("dto");
         */
        String tableName = "biu_user";
        autoBean(tableName);
    }

    /**
     * @param tableName
     * @param type      1:下划线转成下一个字母大写，其它不转
     * @return
     * @throws SQLException
     */
    public static List<FieldData> autoFieldData(String tableName)
            throws SQLException {
        String dto = tableName;
        LOG.out(dbname + "--" + dto);
        list = dto.split(",");

        MysqlHelper db = new MysqlHelper();

        for (int i = 0; i < list.length; i++) {
            lf = new ArrayList<FieldData>();
            String sq = String.format(sql, new Object[]{dbname, list[i]});
            System.out.println("sq:" + sq);
            ResultSet rs = db.query(sq);
            while (rs.next()) {
                String COLUMN_NAME = null;
                try {
                    COLUMN_NAME = rs.getString("COLUMN_NAME");
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String COLUMN_TYPE = rs.getString("COLUMN_TYPE");
                String COLUMN_COMMENT = rs.getString("COLUMN_COMMENT");
                LOG.out(COLUMN_NAME + "-" + COLUMN_TYPE + "--" + COLUMN_COMMENT);
                // COLUMN_NAME = COLUMN_NAME;
                FieldData data = new FormData().getFieldDataInstance(
                        COLUMN_TYPE, COLUMN_NAME, COLUMN_COMMENT);
                lf.add(data);
            }
        }
        //
        return lf;
    }

    /**
     * @param tableName
     * @param type      1:下划线转成下一个字母大写，其它不转
     * @return
     * @throws SQLException
     */
    public static List<FieldData> autoBean(String tableName)
            throws SQLException {
        String dto = tableName;
        LOG.out(dbname + "--" + dto);
        list = dto.split(",");

        MysqlHelper db = new MysqlHelper();

        for (int i = 0; i < list.length; i++) {
            lf = new ArrayList<FieldData>();
            String sq = String.format(sql, new Object[]{dbname, list[i]});
            System.out.println("sq:" + sq);
            ResultSet rs = db.query(sq);
            while (rs.next()) {
                String COLUMN_NAME = null;
                try {
                    COLUMN_NAME = rs.getString("COLUMN_NAME");
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String COLUMN_TYPE = rs.getString("COLUMN_TYPE");
                String COLUMN_COMMENT = rs.getString("COLUMN_COMMENT");
                LOG.out(COLUMN_NAME + "-" + COLUMN_TYPE + "--" + COLUMN_COMMENT);
                COLUMN_NAME = (COLUMN_NAME);
                FieldData data = new FormData().getFieldDataInstance(
                        COLUMN_TYPE, COLUMN_NAME, COLUMN_COMMENT);
                lf.add(data);
            }
            String text = makeJavaString("com.lbb."+AutoGenerationSpringMVC2.project+".entity.dto", list[i], lf, tableName);
            System.out.println("list:");
            for (int j = 0; j < list.length; j++) {
                System.out.println(list[i]);
            }
            System.out.println("lf:");
            for (int j = 0; j < lf.size(); j++) {
                System.out.println(lf.get(j).toString());
            }

            // String textDate=makeJavaString("import java.util.Date;",
            // list[i+1], lf) ;
            LOG.out(text);
            saveFile(list[i], text);
            // saveFile(list[i+1], textDate);
        }
        //
        return lf;
    }

    public static String makeJavaString(String packagename, String classname,
                                        List<FieldData> fields, String tableName) {
        StringBuffer sb = new StringBuffer();
        sb.append("package ").append(packagename).append(";\r");
//		sb.append("import java.util.Date;\r");
//		sb.append("import com.biubiulife.util.DBColumn;  \r");
//		sb.append("import com.biubiulife.util.DBEntity;  \r");
//		sb.append("import com.biubiulife.util.KeyColumn; \r");
        sb.append("import com.baomidou.mybatisplus.annotation.TableField;\r");
        sb.append("import com.baomidou.mybatisplus.annotation.TableId;\r");
        sb.append("import com.baomidou.mybatisplus.annotation.TableLogic;\r");
        sb.append("import com.baomidou.mybatisplus.annotation.TableName;\r");
        sb.append("import com.fasterxml.jackson.annotation.JsonInclude;\r");
        sb.append("import com.fasterxml.jackson.annotation.JsonFormat;\r");
        sb.append("import io.swagger.annotations.ApiModelProperty;\r");
        sb.append("import java.io.Serializable;\r");
        sb.append("import java.math.BigDecimal;\r");
        sb.append("import java.util.Date;\r\n\r\r");

         sb.append("/**                                                         \r");
         sb.append(" * @author  " + AutoGenerationSpringMVC2.author + "                                        \r");
         sb.append(" * @version 1.0.0                                           \r");
         sb.append(" * @since                                                   \r");
         sb.append(" * @Date " + DateUtil.getCurrtime() + "                                                 \r");
         sb.append(" */                                                         \r");

//		sb.append("@DBEntity(\"" + classname + "\")\r");
        sb.append("@TableName(\"" + tableName + "\")\r\n");

        sb.append("public class ")
                .append(replaceLine(FormData.firstUpper(classname.substring(classname.indexOf("_")+1,
                        classname.length())))).append(" {").append("\r");
        for (int i = 0; i < fields.size(); i++) {
            FieldData fd = fields.get(i);
            sb.append("\t/**\r");

            sb.append("\t*" + fd.getNote() + "\r");
            sb.append("\t*/\r");
            String[] s = tableName.split("_");
            String idStr = tableName.substring(tableName.indexOf("_")+1, tableName.length());
            System.out.println("idStr"+idStr);
            if (fd.getField().equals(idStr+"_id")) {
//				sb.append("\t@TableId(useGeneratedKeys=true)                 \r");
//				sb.append("\t@DBColumn(value = \"id\",insertIfNull=\"default\")	  \r");
                sb.append("\t@TableId(\"" + fd.getField() + "\")   \r");

            }

            if (fd.getField().equals("open_id")) {
//				sb.append("\t@TableId(useGeneratedKeys=true)                 \r");
//				sb.append("\t@DBColumn(value = \"id\",insertIfNull=\"default\")	  \r");
                sb.append("\t@TableId(\"" + fd.getField() + "\")   \r");

            }
            else {
                sb.append("\t@ApiModelProperty(value =\"" + fd.getNote() + "\")  \r");
                sb.append("\t@TableField(\"" + fd.getField() + "\")   \r");
                if (fd.getDatatype().startsWith("datetime")){
                    sb.append("\t@JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone=\"GMT+8\")\n");
                }
            }
            sb.append("\t").append("private ")
                    .append(gettypestring(fd.getDatatype())).append(" ")
                    .append(replaceLine(fd.getField())).append(";").append("\r");

            // get
            sb.append("\t").append("public ")
                    .append(gettypestring(fd.getDatatype())).append(" ");
            sb.append("get" + toUpperCaseFirstOne(replaceLine(fd.getField())) + "(){\r");
//			if(fd.getField().contains("time")){
//				sb.append("return DateUtil.getNowTimeStamp();");
//			}
//			else {
            sb.append("\t\treturn " + replaceLine(fd.getField()) + ";\r");
//			}
            sb.append("\t}\r");

            // set
            sb.append("\t").append("public ").append("void").append(" ");
            sb.append("set" + toUpperCaseFirstOne(replaceLine(fd.getField())) + "("
                    + gettypestring(fd.getDatatype()) + "  " + replaceLine(fd.getField())
                    + "){\r");
            sb.append("\t\tthis." + replaceLine(fd.getField()) + "=" + replaceLine(fd.getField()) + ";\r");
            sb.append("\t}\r");
        }
        sb.append("}");
        return sb.toString();
    }

    // 首字母转小写
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder())
                    .append(Character.toLowerCase(s.charAt(0)))
                    .append(s.substring(1)).toString();
    }

    public static String replaceLine(String name) {
		String reName = "";
		String[] split = name.split("_");
		for (int i = 1; i < split.length; i++) {
			split[i] = toUpperCaseFirstOne(split[i]);
		}
		for (int i = 0; i < split.length; i++) {
			reName += split[i];
		}
		return reName;
//        return name;
    }

    // 首字母转大写
    public static String toUpperCaseFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder())
                    .append(Character.toUpperCase(s.charAt(0)))
                    .append(s.substring(1)).toString();
    }

    public static String gettypestring(String dbtype) {
        if (dbtype.startsWith("varchar")) {
            return "String";
        } else if (dbtype.startsWith("bigint")) {
            return "Integer";
        } else if (dbtype.startsWith("int(10)")) {
            return "Integer";
        } else if (dbtype.startsWith("int")) {
            return "Integer";
        } else if (dbtype.startsWith("double")) {
            return "Double";
        } else if (dbtype.startsWith("text")) {
            return "String";
        } else if (dbtype.startsWith("timestamp")) {
            return "Date";
        } else if (dbtype.startsWith("smallint")) {
            return "Integer";
        } else if (dbtype.startsWith("datetime")) {
            return "Date";
        } else if (dbtype.startsWith("decimal")) {
            return "BigDecimal";
        }
        return "";
    }

    public static void saveFile(String classname, String text) {

        System.out.println("text:" + text);
        LOG.out("创建java类：" + classname);
        String filepath = Thread.currentThread().getContextClassLoader()
                .getResource(".").getPath();

        System.out.println("filepath:" + filepath);
        // LOG.out(filepath);

        String[] fileP = filepath.split("target");
        System.out.println(fileP[0]);

        classname = toUpperCaseFirstOne(classname.substring(classname.indexOf("_")+1, classname.length()));

        File file = new File(fileP[0] + "/src/main/java/com/lbb/"+AutoGenerationSpringMVC2.project+"/entity/dto/"
                + replaceLine(FormData.firstUpper(classname)) + ".java");
        /*
         * File file = new File(
         * "F\:\lebaodai\myelicpseWs\trunk\src\main\java\cn\lebaodai\lbd\vo\Msg_push.java");
         */

        if (file.exists()) {
            file.delete();
        }

        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }

        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedWriter writer;
        try {
            writer = new BufferedWriter(
                    new FileWriter(new File(file.getPath())));
            writer.write(text);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
